<template>
  <div id="actionRule">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="135px"
      label-position="right"
      class="addForm"
    >
      <el-form-item label="投票形式">
        <el-radio
          v-for="item in typeList"
          :key="item.value"
          v-model="ruleForm.voteRules.type"
          :label="item.value"
          :disabled="!canEdit"
        >
          {{ item.label }}
        </el-radio>
      </el-form-item>
      <el-form-item
        label="每人每日可投"
        prop="voteRules.dailyVoteNumber"
        v-if="ruleForm.voteRules.type === 'DAILY_VOTE'"
      >
        <el-input-number
          v-model="ruleForm.voteRules.dailyVoteNumber"
          controls-position="right"
          size="small"
          :min="1"
          :max="100"
          :disabled="!canEdit"
        ></el-input-number>
        <span>票</span>
      </el-form-item>
      <el-form-item label="每人最多可为" prop="voteRules.sumVoteNumber" v-else>
        <el-input-number
          v-model="ruleForm.voteRules.sumVoteNumber"
          controls-position="right"
          size="small"
          :min="1"
          :max="100"
          :disabled="!canEdit"
        ></el-input-number>
        <span>名选手投票</span>
      </el-form-item>
      <el-form-item label="提交作品起止时间" prop="submitTime">
        <el-date-picker
          v-model="ruleForm.submitTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="!canEdit"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="投票起止时间" prop="prizeTime">
        <el-date-picker
          v-model="ruleForm.prizeTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="!canEdit"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div v-if="showBtn" class="btn-box">
      <el-button plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button
        type="success"
        :loading="loading"
        @click="confirmLabel('ruleForm')"
      >
        保存
      </el-button>
      <el-button type="primary" @click="nextLab('actionShow')">
        上一步
      </el-button>
      <el-button type="primary" @click="nextLab('userRule')">
        下一步
      </el-button>
    </div>
  </div>
</template>

<script>
import { saveActivities } from '@/api/activeManagement/templatePage' // 接口
import { clearTagMixins } from '@/mixins/clearTag'
export default {
  name: 'aActionRule',
  msg: '活动规则',
  mixins: [clearTagMixins],
  props: ['type', 'subData', 'backPage', 'id'],
  data() {
    return {
      loading: false,
      ruleForm: {
        submitTime: [],
        prizeTime: [],
        submitPostsStartDate: '',
        submitPostsEndDate: '',
        voteRules: {
          //投票规则
          dailyVoteNumber: 1, //每人每日可投票数
          endDate: '', //投票结束时间yyyy-MM-dd hh:mm:ss
          startDate: '', //投票开始时间yyyy-MM-dd hh:mm:ss
          sumVoteNumber: 1, //每人可为几人投票
          type: 'DAILY_VOTE' //投票形式: 每人每日均可投票 DAILY_VOTE; 一次性投票 SUM_VOTE
        }
      },
      defaultRuleForm: {
        submitTime: [],
        prizeTime: [],
        submitPostsStartDate: '',
        submitPostsEndDate: '',
        voteRules: {
          //投票规则
          dailyVoteNumber: 1, //每人每日可投票数
          endDate: '', //投票结束时间yyyy-MM-dd hh:mm:ss
          startDate: '', //投票开始时间yyyy-MM-dd hh:mm:ss
          sumVoteNumber: 1, //每人可为几人投票
          type: 'DAILY_VOTE' //投票形式: 每人每日均可投票 DAILY_VOTE; 一次性投票 SUM_VOTE
        }
      },
      rules: {
        submitTime: {
          type: 'array',
          required: true,
          message: '请选择提交作品起止时间',
          trigger: 'blur'
        },
        prizeTime: {
          type: 'array',
          required: true,
          message: '请选择投票起止时间',
          trigger: 'blur'
        },
        'voteRules.dailyVoteNumber': {
          required: true,
          message: '请选择每人每日可投数量',
          trigger: 'blur'
        },
        'voteRules.dailyVoteNumber': {
          required: true,
          message: '请选择每人可为几人投票',
          trigger: 'blur'
        }
      },
      typeList: [
        { value: 'DAILY_VOTE', label: '每人每日可投票' },
        { value: 'SUM_VOTE', label: '一次性投票' }
      ],
      canEdit: true,
      isSave: false //是否保存
    }
  },
  computed: {
    showBtn() {
      //是否显示保存按钮
      return this.type === 'add' || this.type === 'edit'
    }
  },
  watch: {
    'ruleForm.submitTime': {
      //提交作品
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 1) {
          this.ruleForm.submitPostsStartDate = newVal[0]
          this.ruleForm.submitPostsEndDate = newVal[1]
        } else {
          this.ruleForm.submitPostsStartDate = ''
          this.ruleForm.submitPostsEndDate = ''
        }
      },
      deep: true
    },
    'ruleForm.prizeTime': {
      //投票起止时间
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 1) {
          this.ruleForm.voteRules.startDate = newVal[0]
          this.ruleForm.voteRules.endDate = newVal[1]
        } else {
          this.ruleForm.voteRules.startDate = ''
          this.ruleForm.voteRules.endDate = ''
        }
      },
      deep: true
    },
    subData(newV) {
      if (newV.activityAuditing) {
        this.getCanEdit()
      }
      if (newV.rules) {
        let r = newV.rules
        this.ruleForm = Object.assign({}, { submitTime: [], prizeTime: [] }, r)
        if (r.submitPostsStartDate && r.submitPostsEndDate) {
          this.ruleForm.submitTime = [
            r.submitPostsStartDate,
            r.submitPostsEndDate
          ]
        } else {
          this.ruleForm.submitTime = []
        }
        if (r.voteRules.startDate && r.voteRules.endDate) {
          this.ruleForm.prizeTime = [r.voteRules.startDate, r.voteRules.endDate]
        } else {
          this.ruleForm.prizeTime = []
        }
      } else {
        this.ruleForm = { ...this.defaultRuleForm }
        this.ruleForm.submitTime = []
        this.ruleForm.prizeTime = []
      }
    }
  },
  mounted() {},
  methods: {
    getCanEdit() {
      this.canEdit =
        (this.type === 'add' || this.type === 'edit') &&
        this.subData.activityAuditing.twoAuditing.auditingState !== 'PASS'
    },
    resetIsSave() {
      this.isSave = false
    },
    /*取消*/
    cancelLabel() {
      if (this.isSave) {
        this.clearTag()
      } else {
        this.$confirm(
          '您的信息尚未保存，取消后所填写的信息将不被保存，确定要退出？',
          '提示',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存后退出',
            cancelButtonText: '直接退出',
            type: 'warning'
          }
        )
          .then(() => {
            this.confirmLabel('ruleForm').then((response) => {
              this.clearTag()
            })
          })
          .catch((action) => {
            if (action === 'cancel') {
              this.clearTag()
            }
          })
      }
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
      // let query = {
      //   mId: this.$route.query.mId
      // }
      // this.$router.replace({ name: this.backPage, query: query })
    },
    /*保存*/
    confirmLabel(formName) {
      let _this = this
      return new Promise((resolve, reject) => {
        _this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.loading = true
            let rules = { ..._this.ruleForm }
            delete rules.submitTime
            delete rules.prizeTime
            saveActivities(
              _this.id,
              { rules },
              (response) => {
                _this.$message.success('保存成功')
                _this.loading = false
                _this.isSave = true
                resolve(true)
              },
              (response) => {
                _this.$message.warning(response.message)
                _this.loading = false
                reject()
              }
            )
          } else {
            return false
          }
        })
      })
    },
    /*下一步*/
    nextLab(labName) {
      this.confirmLabel('ruleForm').then((response) => {
        this.$emit('changeLab', labName)
      })
    }
  }
}
</script>

<style lang="less">
#actionRule {
  .el-range__icon {
    line-height: 25px;
  }
  .el-range-separator {
    line-height: 25px;
  }
  .el-input-number.is-controls-right[class*='small'] [class*='increase'] {
    top: 2px;
    line-height: 14px;
  }
  .el-input-number + span {
    margin-left: 5px;
  }
}
</style>
